package org.hhf.persistence;

import org.hhf.core.RedisCore;

import java.io.*;
import java.nio.file.*;
import java.util.*;

/**
 * 简化的持久化管理器
 */
public class PersistenceManager {
    private final RedisCore core;
    private final String dataDir;
    
    public PersistenceManager(RedisCore core, String dataDir) {
        this.core = core;
        this.dataDir = dataDir;
        try {
            Files.createDirectories(Paths.get(dataDir));
        } catch (IOException e) {
            System.err.println("Failed to create data directory: " + e.getMessage());
        }
    }
    
    /**
     * 保存数据到文件
     */
    public void save() {
        String filePath = dataDir + "/dump.txt";
        try (PrintWriter writer = new PrintWriter(new FileWriter(filePath))) {
            Set<String> keys = core.keys();
            for (String key : keys) {
                Object value = core.get(key);
                if (value != null) {
                    writer.println(key + "=" + value.toString());
                }
            }
            System.out.println("Data saved to " + filePath);
        } catch (IOException e) {
            System.err.println("Failed to save data: " + e.getMessage());
        }
    }
    
    /**
     * 从文件加载数据
     */
    public void load() {
        String filePath = dataDir + "/dump.txt";
        File file = new File(filePath);
        if (!file.exists()) {
            return;
        }
        
        try (BufferedReader reader = new BufferedReader(new FileReader(filePath))) {
            String line;
            while ((line = reader.readLine()) != null) {
                int equalIndex = line.indexOf('=');
                if (equalIndex > 0) {
                    String key = line.substring(0, equalIndex);
                    String value = line.substring(equalIndex + 1);
                    core.put(key, value, RedisCore.DataType.STRING);
                }
            }
            System.out.println("Data loaded from " + filePath);
        } catch (IOException e) {
            System.err.println("Failed to load data: " + e.getMessage());
        }
    }
    
    /**
     * 记录命令到日志
     */
    public void logCommand(String command, String... args) {
        String filePath = dataDir + "/commands.log";
        try (PrintWriter writer = new PrintWriter(new FileWriter(filePath, true))) {
            writer.print(command);
            for (String arg : args) {
                writer.print(" " + arg);
            }
            writer.println();
        } catch (IOException e) {
            System.err.println("Failed to log command: " + e.getMessage());
        }
    }
}